const path = require("path");
const fse = require("fs-extra");
const joinFiltersToProject = async (comm, projectCode) => {
  try {
    // 验证 projectCode 格式
    if (!/^[a-zA-Z0-9-_]+$/.test(projectCode)) {
      throw new Error("Invalid projectCode format");
    }

    const url = path.join(__dirname, "../../../projects", projectCode, "src/filters/config.js");

    let filtersContent = fse.readFileSync(url, "utf8");

    // 合并所有 replace 操作为一次正则替换
    filtersContent = filtersContent
      .replace(/export\s+default\s+/g, "")
      .replace(/\s/g, "")
      .replace(/([a-zA-Z0-9-_]+):/g, '"$1":')
      .replace(/,?};/, "}");
    console.log(filtersContent, "filtersContent");
    let filters = JSON.parse(filtersContent);

    if (comm.options && typeof comm.options === 'string' && comm.options.includes("Filters.list")) {
      const key = comm.options.replace(/Filters\.list\(|\)/g, "").trim();

      if (!key) {
        return;
      }

      if (comm.filterObj && typeof comm.filterObj === 'object') {
        if (!filters[key] || JSON.stringify(filters[key]) !== JSON.stringify(comm.filterObj)) {
          filters = { ...filters, ...comm.filterObj };
          fse.outputFileSync(url, `export default ${JSON.stringify(filters)}`, "utf8");
        }
      }
    }

  } catch (error) {
    console.error("Error processing filters:", error);
    throw error;
  }
};

module.exports = joinFiltersToProject;